from flask import request, make_response
import redis
import utils


class UserLogin:
    @staticmethod
    def get_register():
        db = redis.Redis(host="localhost", port=6379, decode_responses=True)
        res = {
            "ok": True
        }

        data = request.get_json()
        user_id = data["id"]
        password = data["password"]
        user_type = data["type"]

        if not user_id or not password:
            res["ok"] = False
        else:
            db.hset(user_id, "password", password)
            db.hset(user_id, "type", user_type)
            db.hset(user_id, "balance", "0")
        return make_response(res)

    @staticmethod
    def get_login():
        db = redis.Redis(host="localhost", port=6379, decode_responses=True)
        res = {
            "ok": True
        }

        data = request.get_json()
        user_id = data["id"]
        password = data["password"]
        user_type = data["type"]

        if not user_id or not password:
            res["ok"] = False
        else:
            db_password = db.hget(user_id, "password")
            db_type = db.hget(user_id, "type")
            if password != db_password or user_type != db_type:
                res["ok"] = False
        return make_response(res)

    @staticmethod
    def set_password():
        db = redis.Redis(host="localhost", port=6379, decode_responses=True)
        res = {
            "ok": True
        }

        data = request.get_json()
        user_id = data["id"]
        password = data["password"]
        new_password = data["new"]

        if not user_id or not password or not new_password:
            res["ok"] = False
        else:
            db_password = db.hget(user_id, "password")
            if password != db_password:
                res["ok"] = False
            else:
                db.hset(user_id, "password", new_password)
        return make_response(res)


